<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>尬聊-聊天室</title>
    <%- include common %>

    <style>
        #chatroom{
            width:300px;
            height:460px;
            border:1px solid darkgoldenrod;
            border-radius: 10px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <%- include("head",{title:"chat",username})%>

    <h2 id="title" data-username="<%- username %>"> 尬聊-聊天室 </h2> 
    <div id="chatroom">

    </div>
    <input type="text" placeholder="请输入聊天内容" id="word"  >
    <button type="button" id="sendbtn">点击发送 </button>
    <%- include foot %>
    <script>
        // 客户端
        // # 客户端 
        // 1. 连接服务器
        // 2. 发送消息到服务器
        // 3. 监听服务器转发过来的消息
        // 4. 监听服务器端的关闭 

        var ws = new WebSocket("ws://192.168.60.56:4100");  // 1. 连接服务器
        // 判断是否连接成功
        var username = $("#title").attr("data-username");
        ws.onopen = function(){
            // username  = prompt("请输入你的用户名.");
            console.log(username);
            // 2. 发送消息到服务器
            // ws.send(`${username} 说: hello ~ `)
            sendMsg(' hello...  我上线了  ~',"green")
        }

         // 3. 监听服务器转发过来的消息
        ws.onmessage = function(data){
            console.log(data)
            document.getElementById("chatroom").innerHTML += `${data.data}`
        }

        function sendMsg(msg,color){
            var time = new Date();
            var hour = time.getHours();
            var min = time.getMinutes();
            ws.send(`<p style="color:${color} "> ${username} (${hour}:${min} ) 说: ${msg} </p> `)
        }

        sendbtn.onclick = function(){
            sendMsgByClick()
        }

        function sendMsgByClick(){
            sendMsg(word.value,'#666');
            word.value = ""
        }

        document.onkeydown = function(e){
            if(e.keyCode == 13){
                sendMsgByClick()
            }
        }

        // 4. 监听服务器端的关闭 和异常 
        ws.onclose = function(){
            alert("服务器突然关闭了...")
        }
        ws.onerror = function(){
            alert("服务器端突然死机了...")
        }
    </script>
</body>
</html>